import React, { Component } from "react";
import { Form, Icon, Input, Button, Alert, message, Table, List, Typography, Divider } from "antd";
import { Link } from 'react-router-dom';
import { getStudentAndOtherRoleInOutRecord, getSchoolUserTypeCount, getSchoolNameById, getStudentInOutRecordDetail, getInOutRecordDetailStudentName } from '../js/kaoqinpushdetail.js'
import '../css/kaoqinpushdetail.css';
import '../css/statisticword.css'
import { Spin } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';
//echarts5.0按需引入
import * as echarts from 'echarts/core';
import {
    BarChart, PieChart, LineChart
} from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    GridComponent
} from 'echarts/components';
import {
    CanvasRenderer
} from 'echarts/renderers';
echarts.use(
    [TitleComponent, TooltipComponent, GridComponent, BarChart, PieChart, LineChart, CanvasRenderer]
);
const WX = require("jweixin-wechat");
const antIcon = <LoadingOutlined style={{ fontSize: 25 }} spin />;
const chartStyle = {
    width: '400px',
    height: '273px',
    margin: '0 0 0 -0.6px'
}
let studentTotal = 0
let otherTotal = 0
let schoolId = 0
let dateTime = ''
let startTime = ''
let endTime = ''

class KaoqinpushStatistics extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dateTime: '',
            otherRoleInTimes: 0,
            otherRoleOutTimes: 0,
            studentInTimesList: [],
            studentOutTimesList: [],
            loading: true
        };
    }
    componentDidMount() {
        this.refreshdata();
    }
    refreshdata() {
        //获取链接中携带的参数----学校Id
        let urlData = this.getUrlParam('state');
        let urlData2 = this.getUrlParam('time');
        schoolId = urlData.split('=')[1].replace('#', '');
        dateTime = urlData2.split("=")[1].replace('&', '');
        console.log("dateTime", dateTime)
        startTime = dateTime.split(' ')[0] + ' 00:00:00'
        endTime = dateTime
        this.setState({
            dateTime: dateTime
        })
        getSchoolNameById(schoolId)
            .then((res) => {
                this.setState({
                    schoolName: res.data.schoolName,
                    schoolId: schoolId,
                    startTime: startTime,
                    endTime: endTime
                })
            });
        getSchoolUserTypeCount(schoolId)
            .then((res) => {
                otherTotal = res.data.otherTotal
                studentTotal = res.data.studentTotal
                this.setState({
                    studentTotal: res.data.studentTotal,
                    otherTotal: res.data.otherTotal
                })
            });
        let studentInTimesList = []
        let studentOutTimesList = []
        let otherRoleInTimes = 0
        let otherRoleOutTimes = 0
        getStudentAndOtherRoleInOutRecord(schoolId, startTime, endTime)
            .then((res) => {
                res.data.studentInOutList.forEach((item, index) => {
                    studentInTimesList.push({
                        value: item.inTimes,
                        name: item.grades
                    })
                    studentOutTimesList.push({
                        value: item.outTimes,
                        name: item.grades
                    })
                })
                otherRoleInTimes = res.data.teacherInOutList[0].inTimes
                otherRoleOutTimes = res.data.teacherInOutList[0].outTimes
                this.setState({
                    studentInTimesList: studentInTimesList,
                    studentOutTimesList: studentOutTimesList,
                    otherRoleInTimes: otherRoleInTimes,
                    otherRoleOutTimes: otherRoleOutTimes,
                    loadding: false
                })
            })
    }
    //获取链接中携带的参数方法
    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    //    let url = '?code=asdasdasdasd&time=2021-01-25 23:57:00&state=37'
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        //window.location.search
        if (r != null) {
            return unescape(r[0]);
        }
        return null; //返回参数值
    }
    //获取当前时间y-m-d
    getCurTime(dateTime) {
        var date = new Date(dateTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let time = y + '-' + m + '-' + d;  //这里如果不需要小时 分  后边的可以不需要拼接
        return time
    }
    //获取当前时间y-m-d h-m
    getCurTime2(dateTime) {
        var date = new Date(dateTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        let time = y + '-' + m + '-' + d + ' ' + h + ':' + minute; //这里如果不需要小时 分  后边的可以不需要拼接
        return time
    }
    render() {
        return (
            <div>
                <div className="title">
                    {this.state.schoolName}
                </div>
                <div className="numTag">
                    <div className="numTag-user">
                        学生总人数 | {this.state.studentTotal}
                    </div>
                    <div className="numTag-user">
                        教职工总人数 | {this.state.otherTotal}
                    </div>
                </div>
                <div className="numTag2">
                    <div className="numTag-time">
                        统计时间 : {this.state.endTime}
                    </div>
                </div>
                <div className="echart-content">
                    <div className="echart-detail">
                        <div className="echart-title">
                            1、学生到校考勤统计 <Spin indicator={antIcon} spinning={this.state.loadding} />
                        </div>
                        <Link to={{
                            pathname: '/KaoqinpushDetail',
                            state: {
                                enter: 'in'
                            }
                        }}
                            style={{ color: 'green', margin: 'auto', fontSize: '18px' }}>
                            <div>详情</div>
                        </Link>
                    </div>
                    <Echarts1 studentInTimesList={this.state.studentInTimesList} />
                </div>
                <div className="echart-content">
                    <div className="echart-detail">
                        <div className="echart-title">
                            2、学生离校考勤统计 <Spin indicator={antIcon} spinning={this.state.loadding} />
                        </div>
                        <Link to={{
                            pathname: '/KaoqinpushDetail',
                            state: {
                                enter: 'out'
                            }
                        }}
                            style={{ color: 'green', margin: 'auto', fontSize: '18px' }}>
                            <div>详情</div>
                        </Link>
                    </div>
                    <Echarts2 studentOutTimesList={this.state.studentOutTimesList} />
                </div>
                <div className="echart-content">
                    <div className="echart-detail">
                        <div className="echart-title">
                            3、教职工到/离校考勤统计
                        </div>
                        {/* <Link to="/KaoqinpushDetail" style={{ color: 'green', margin: 'auto', fontSize:'18px'}}>
                            <div>详情</div>
                        </Link> */}
                    </div>
                    <Echarts3 otherRoleInTimes={this.state.otherRoleInTimes}
                        otherRoleOutTimes={this.state.otherRoleOutTimes} />
                </div>
            </div>
        )
    }
}

class KaoqinpushDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schoolId: schoolId,
            startTime: startTime,
            endTime: endTime,
            studentTotal: studentTotal,
        };
    }
    componentWillMount() {
        if (this.props.location.state.enter != undefined && this.props.location.state.enter !== null) {
            sessionStorage.setItem("enter", this.props.location.state.enter);
        }
        console.log("enter", sessionStorage.getItem("enter"))
    }
    componentDidMount() {
        this.setState({
            loadding: true
        })
        this.refreshdata();
    }
    refreshdata() {
        let studentGradeInOutList = []
        // let studentGradeOutList = []
        let inTotal = 0
     //   let unInTotal = 0
        let outTotal = 0
     //   let unOutTotal = 0
        let unrecordTotal = 0
        getStudentInOutRecordDetail(this.state.schoolId, this.state.startTime, this.state.endTime)
            .then((res) => {
                console.log("res.data.studentGradeInOutList", res.data.studentGradeInOutList)
                res.data.studentGradeInOutList.forEach((item, index) => {
                    studentGradeInOutList.push({
                        inTimes: item.inTimes,
                        outTimes: item.outTimes,
                        unrecord :item.unrecord,
                        grades: item.grades
                    })
                    inTotal += item.inTimes
                    outTotal += item.outTimes
                    unrecordTotal += item.unrecord
                })
                this.setState({
                    schoolName: res.data.schoolName,
                    studentGradeInOutList: studentGradeInOutList,
                //    studentGradeOutList: studentGradeOutList,
                    inTotal: inTotal,
               //     unInTotal: unInTotal,
                    outTotal: outTotal,
                    unrecordTotal : unrecordTotal,
               //     unOutTotal: unOutTotal,
                    loadding: false
                })
            });
    }
    onRowSelectIn = (record, index) => {
        return {
            onClick: (e) => {
                this.props.history.push({
                    pathname: '/KaoqinpushStudentName',
                    state: {
                        grade: record.grades

                    }
                });
            }
        }
    }
    onRowSelectOut = (record, index) => {
        return {
            onClick: (e) => {
                this.props.history.push({
                    pathname: '/KaoqinpushStudentName',
                    state: {
                        grade: record.grades
                    }
                });
            }
        }
    }
    render() {
        if (sessionStorage.getItem('enter') === 'in') {
            const columns = [
                {
                    title: '具体班级',
                    dataIndex: 'grades',
                },
                {
                    title: '在校',
                    dataIndex: 'inTimes',
                },
                {
                    title: '离校',
                    dataIndex: 'outTimes',
                },
                {
                    title: '未记录',
                    dataIndex: 'unrecord',
                },
            ];
            return (
                <div>
                    <div className="title">
                        <Spin indicator={antIcon} spinning={this.state.loadding} />
                    </div>
                    <div className="numTag">
                        <div className="numTag-user">
                            当前在校{this.state.inTotal}人
                        </div>
                        <div className="numTag-user">
                            离校{this.state.outTotal}人
                        </div>
                        <div className="numTag-user">
                            未记录{this.state.unrecordTotal}
                        </div>
                    </div>
                    <div className="numTag2">
                        <div className="numTag-time">
                            统计时间 : {this.state.endTime}
                        </div>
                    </div>
                    <div className="tableFont">
                        {/* <a slot="outTimes" slot-scope="text">{{ text }}</a> */}
                        <Table columns={columns} dataSource={this.state.studentGradeInOutList} size="large"
                            onRow={this.onRowSelectIn}
                        />
                    </div>

                </div>
            )
        } else if (sessionStorage.getItem('enter') == 'out') {
            const columns = [
                {
                    title: '具体班级',
                    dataIndex: 'grades',
                },
                {
                    title: '离校',
                    dataIndex: 'outTimes',
                },
                {
                    title: '在校',
                    dataIndex: 'inTimes',
                },
                {
                    title: '未记录',
                    dataIndex: 'unrecord',
                },
            ];
            return (
                <div>
                    <div className="title">
                        <Spin indicator={antIcon} spinning={this.state.loadding} />
                    </div>
                    <div className="numTag">
                        <div className="numTag-user">
                            当前离校{this.state.outTotal}人
                        </div>
                        <div className="numTag-user">
                            在校{this.state.inTotal}人
                        </div>
                        <div className="numTag-user">
                            未记录{this.state.unrecordTotal}
                        </div>
                    </div>
                    <div className="numTag2">
                        <div className="numTag-time">
                            统计时间 : {this.state.endTime}
                        </div>
                    </div>
                    <div className="tableFont">
                        {/* <a slot="outTimes" slot-scope="text">{{ text }}</a> */}
                        <Table columns={columns} dataSource={this.state.studentGradeInOutList} size="large"
                            onRow={this.onRowSelectOut}
                        />
                    </div>

                </div>
            )
        }

    }
}
class KaoqinpushStudentName extends Component {
    constructor(props) {
        super(props)
        this.state = {
            schoolId: schoolId,
            startTime: startTime,
            endTime: endTime
        }
    }
    componentWillMount() {
        if (this.props.location.state.grade != undefined && this.props.location.state.grade !== null) {
            sessionStorage.setItem("grade", this.props.location.state.grade);
        }
        console.log("grade", sessionStorage.getItem("grade"))
        this.setState({
            grade: sessionStorage.getItem("grade"),
            enter: sessionStorage.getItem('enter')
        })
    }
    componentDidMount() {
        this.refreshdata();
    }
    refreshdata() {
        let inStudentNameList = []
        let outStudentNameList = []
        let unRecordList =[]
        let inCount = 0
        let outCount = 0
        let unRecord = 0
        getInOutRecordDetailStudentName(this.state.schoolId, this.state.startTime, this.state.endTime, this.state.enter, this.state.grade)
            .then((res) => {
                console.log("InOutRecordStudentNameList", res.data)
                res.data.InOutRecordStudentNameList.forEach((item, index) => {
                    if (item.status == 'in') {
                        inStudentNameList.push(
                            item.name
                        )
                        inCount = inStudentNameList.length
                    } else if(item.status == 'out'){
                        outStudentNameList.push(
                            item.name
                        )
                        outCount = outStudentNameList.length
                    }else if(item.status == 'no'){
                        unRecordList.push(
                            item.name
                        )
                        unRecord = unRecordList.length
                    }
                })
                this.setState({
                    inStudentNameList: inStudentNameList,
                    inCount: inCount,
                    outStudentNameList: outStudentNameList,
                    outCount: outCount,
                    unRecordList:unRecordList,
                    unRecord:unRecord
                })
            });
    }
    render() {
        if (sessionStorage.getItem('enter') == 'in')
            return (
                <div>
                    <div className="title">
                        {this.state.grade}
                    </div>
                    <div className="numTag">
                        <div className="numTag-user">
                            在校{this.state.inCount}人
                        </div>
                        <div className="numTag-user">
                            离校{this.state.outCount}人
                        </div>
                        <div className="numTag-user">
                            未记录{this.state.unRecord}人
                        </div>
                    </div>
                    <div className="studentlistUnIn">
                        <List
                            header={<div>{this.state.grade}离校学生列表</div>}
                            size='large'
                            dataSource={this.state.outStudentNameList}
                            renderItem={item => (
                                <List.Item>
                                    <div className="studentlistUnIn-item">
                                        {item}
                                    </div>
                                </List.Item>
                            )}
                        />
                    </div>
                    <div className="studentlistUnIn">
                        <List
                            header={<div>{this.state.grade}未记录学生列表</div>}
                            size='large'
                            dataSource={this.state.unRecordList}
                            renderItem={item => (
                                <List.Item>
                                    <div className="studentlistUnIn-item">
                                        {item}
                                    </div>
                                </List.Item>
                            )}
                        />
                    </div>
                    <List
                        header={<div>{this.state.grade}在校学生列表</div>}
                        size='large'
                        dataSource={this.state.inStudentNameList}
                        renderItem={item => (
                            <List.Item>
                                <div className="studentlistIn-item">
                                    {item}
                                </div>
                            </List.Item>
                        )}
                    />
                </div>
            )
        else if (sessionStorage.getItem('enter') == 'out') {
            return (
                <div>
                    <div className="title">
                        {this.state.grade}
                    </div>
                    <div className="numTag">
                        <div className="numTag-user">
                            离校{this.state.outCount}人
                        </div>
                        <div className="numTag-user">
                            在校{this.state.inCount}人
                        </div>
                        <div className="numTag-user">
                            未记录{this.state.unRecord}人
                        </div>
                    </div>
                    <div className="studentlistUnOut">
                        <List
                            header={<div>{this.state.grade}在校学生列表</div>}
                            bordered
                            dataSource={this.state.inStudentNameList}
                            renderItem={item => (
                                <List.Item>
                                    <div className="studentlistUnOut-item">
                                        {item}
                                    </div>
                                </List.Item>
                            )}
                        />
                    </div>
                    <div className="studentlistUnOut">
                        <List
                            header={<div>{this.state.grade}未记录学生列表</div>}
                            bordered
                            dataSource={this.state.unRecordList}
                            renderItem={item => (
                                <List.Item>
                                    <div className="studentlistUnOut-item">
                                        {item}
                                    </div>
                                </List.Item>
                            )}
                        />
                    </div>
                    <List
                        header={<div>{this.state.grade}离校学生列表</div>}
                        bordered
                        dataSource={this.state.outStudentNameList}
                        renderItem={item => (
                            <List.Item>
                                <div className="studentlistOut-item">
                                    {item}
                                </div>
                            </List.Item>
                        )}
                    />
                </div>
            )
        }
    }
}

class Echarts1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            studentInTimesList: props.studentInTimesList,
        }
    }
    componentWillReceiveProps(props) {
        if (JSON.stringify(props.studentInTimesList) != JSON.stringify(this.state.studentInTimesList)) {
            this.setState({
                studentInTimesList: props.studentInTimesList
            }, () => {
                this.drawChart();
            })
        } else {
            this.drawChart();
        }
    }

    drawChart() {
        let chart = echarts.init(document.getElementById('s1'));
        chart.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            series: [
                {
                    type: 'pie',
                    radius: ['30%', '45%'],
                    center: ['50%', '50%'],
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: '{b} : {c}',
                                textStyle: {
                                    fontSize: 16
                                },
                            },
                            labelLine: { show: true }
                        }
                    },
                    data: this.state.studentInTimesList
                }
            ]
        })
        window.onresize = chart.resize;
    }
    render() {
        return (
            <div>
                <div id='s1' style={chartStyle}>
                </div>
            </div>
        )
    }
}
class Echarts2 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            studentOutTimesList: props.studentOutTimesList
        }
    }
    componentWillReceiveProps(props) {
        if (JSON.stringify(props.studentOutTimesList) != JSON.stringify(this.state.studentOutTimesList)) {
            this.setState({
                studentOutTimesList: props.studentOutTimesList
            }, () => {
                this.drawChart();
            })
        } else {
            this.drawChart();
        }
    }

    drawChart() {
        let chart = echarts.init(document.getElementById('s2'));
        chart.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            title: {
                left: 'center',
                top: '10px'
            },
            series: [
                {
                    type: 'pie',
                    radius: ['30%', '45%'],
                    center: ['50%', '50%'],
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: '{b} : {c}',
                                textStyle: {
                                    fontSize: 16
                                },
                            },
                            labelLine: { show: true }
                        }
                    },
                    data: this.state.studentOutTimesList
                }
            ]
        })
        window.onresize = chart.resize;
        chart.hideLoading()
    }
    render() {
        return (
            <div>
                <div id='s2' style={chartStyle}>
                </div>
            </div>
        )
    }
}
class Echarts3 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            otherRoleInTimes: props.otherRoleInTimes,
            otherRoleOutTimes: props.otherRoleOutTimes
        }
    }
    componentWillReceiveProps(props) {
        if (JSON.stringify(props.otherRoleInTimes) != JSON.stringify(this.state.otherRoleInTimes) ||
            JSON.stringify(props.otherRoleOutTimes) != JSON.stringify(this.state.otherRoleOutTimes)) {
            this.setState({
                otherRoleInTimes: props.otherRoleInTimes,
                otherRoleOutTimes: props.otherRoleOutTimes
            }, () => {
                this.drawChart();
            })
        } else {
            this.drawChart();
        }
    }

    drawChart() {
        let chart = echarts.init(document.getElementById('s3'));
        chart.setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            title: {
                left: 'center',
                top: '10px'
            },
            series: [
                {
                    type: 'pie',
                    radius: ['30%', '45%'],
                    center: ['50%', '50%'],
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                formatter: '{b} : {c}',
                                textStyle: {
                                    fontSize: 16
                                },
                            },
                            labelLine: { show: true }
                        }
                    },
                    data: [
                        { value: this.state.otherRoleInTimes, name: '到校' },
                        { value: this.state.otherRoleOutTimes, name: '离校' },
                    ]
                }
            ]
        })
        window.onresize = chart.resize;
    }
    render() {
        return (
            <div>
                <div id='s3' style={chartStyle}>
                </div>
            </div>
        )
    }
}



export { KaoqinpushStatistics, KaoqinpushDetail, KaoqinpushStudentName, Echarts1, Echarts2, Echarts3 }
export default KaoqinpushStatistics;
